package org.example.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.UUID;

@Controller
@Slf4j
public class FileController {

    @Autowired
    private StorageService storageService;

    @GetMapping("/")
    public String home() {
        return "index";
    }

    @GetMapping("/about")
    public String about() {
        return "about";
    }

    @GetMapping("/file")
    public String file() {
        return "index";
    }

    @PostMapping("/file")
    public String upload(@RequestParam("file1") MultipartFile uploadedFile) throws IOException {
        if (uploadedFile.isEmpty()) {
            log.info("no file uploaded.");
            return "index";
        }
        String savePath = getSavePath(uploadedFile);
        storageService.save(uploadedFile, savePath);
        return "index";
    }

    private static final boolean USE_RANDOM_SAVE_PATH = false;

    private String getSavePath(MultipartFile uploadedFile) {
        if (USE_RANDOM_SAVE_PATH) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            return "%s/%s/%s".formatted(
                    uuid.substring(0, 2),
                    uuid.substring(2),
                    uploadedFile.getOriginalFilename());
        }
        return uploadedFile.getOriginalFilename();
    }
}
